package com.example.lib_repair.detail

import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Bundle
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.viewbinding.ViewBinding
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.example.lib_common.mvi.BaseActivity
import com.example.lib_repair.ApiService
import com.example.lib_repair.RepairEntity
import com.example.lib_repair.databinding.ActivityDetailBinding
import com.example.network_sdk.HttpType
import com.example.network_sdk.NetWorkFactory
import com.google.gson.Gson
import com.wildma.pictureselector.PictureBean
import com.wildma.pictureselector.PictureSelector
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import me.shouheng.compress.Compress
import me.shouheng.compress.strategy.Strategies
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File


@Route(path = "/repair/DetailRepair")
class DetailRepair : BaseActivity<ActivityDetailBinding,DetailViewModel>() {
    override fun createVM(): DetailViewModel {
        return DetailViewModel()
    }

    override fun createViewBinding(): ViewBinding {
        return ActivityDetailBinding.inflate(inflater)
    }
    var repairId =0
    lateinit var picName : String
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        bindState()
        v.backBtn.setOnClickListener { finish() }
        val stringExtra = intent.getStringExtra("page")
        if (stringExtra=="维修"){
            val repairList = intent.getSerializableExtra("repair") as RepairEntity
            val map = HashMap<String,Any>()
            repairId=repairList.repairId
            map["repairId"]=repairList.repairId
            vm.requestDetail(map)

            v.startDate.text=repairList.repairData
            v.applyDate.text=repairList.repairTime
            v.detailDes.setText(repairList.repairDescribe)
            v.carSub.text="维修"
            v.carSub.setOnClickListener {
                val map1 = HashMap<String,Any>()
                map1["repairId"]=repairList.repairId
                map1["repairStatues"]=2
                map1["repairUserId"]=repairList.repairUserId
                vm.requestComplete(map1)
            }
        }else{
            v.carSub.text="添加"
            v.carSub.setOnClickListener {
                val map = HashMap<String,Any>()
                map["departmentId"]=0
                map["repairData"]="2020-07-11"
                map["repairDescribe"]=v.detailDes.text.toString()
                map["repairId"]=10
                map["repairTime"]="2020-07-11"
                map["repairUserId"]=0
                map["userId"]=SPUtils.getInstance().getInt("uId")
                vm.requestAdd(map)
            }
        }
        v.userName.text=SPUtils.getInstance().getString("uName")
        v.belong.text=SPUtils.getInstance().getString("department")
        v.addImg.setOnClickListener {
            PictureSelector.create(this,PictureSelector.SELECT_REQUEST_CODE).selectPicture(false)
        }
    }
    private fun bindState() {
        lifecycleScope.launch(Dispatchers.Main){
            repeatOnLifecycle(Lifecycle.State.STARTED){
                vm.mutableContainer.uiStateFlow.collect{
                    var gson =Gson()
                    val toJson = gson.toJson(it.entity.values)
                    LogUtils.e("====img${toJson.toString()},\n=====${it.entity.msg}")
                    if (it.entity.msg=="成功"){
                        if (it.entity.values.apply!!.imgs!=null){
                            val imgs = it.entity.values.apply!!.imgs
                            v.addImg.background=null
                            Glide.with(this@DetailRepair).load(imgs!![0]).into(v.addImg)
                        }
                    }
                    if (it.entity1.msg=="添加成功"){
                        val map = HashMap<String,Any>()
                        map["imgId"]=Math.random()*10011
                        map["repairId"]=it.entity1.values.repairId
                        map["repairPath"]="http://118.195.161.134:8077/fileDownload?fileName\\"+"1658142366739.jpeg"
                        vm.requestAddImg(map)
                        finish()
                    }
                    if (it.entity2.statuesCode==200){
                        finish()
                    }
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode==PictureSelector.SELECT_REQUEST_CODE&&data!=null){
            val bean = data.extras!!.get(PictureSelector.PICTURE_RESULT) as PictureBean
            compress(bean.path)
        }
    }

    private fun compress(path: String?) {
        var file= File(path)
        lifecycleScope.launch(Dispatchers.IO){
            var compress = Compress.with(this@DetailRepair, file)
                .strategy(Strategies.luban())
                .setIgnoreSize(100,true)
                .get()
            val requestBody = RequestBody.create(MediaType.parse("multipart/form-data"),compress)
            val imgpart = MultipartBody.Builder().addFormDataPart("file",compress.name,requestBody).build().parts()
            NetWorkFactory.factory(HttpType.NONE)!!
                .create(ApiService::class.java)
                .uploadIms(imgpart)
                .collect{
                    launch (Dispatchers.Main){
                        println("==========${it.msg}")
                        if (it.statuesCode==200){
                            LogUtils.e("====路径名:${compress.name}")
                        }
                    }
                }
        }
    }
}